<template>
  <div class="contribute">
    <div class="contribute-contain">
      <div class="handle-box">
        <el-input class="handle-input" v-model="search_text" placeholder="请输入视频名关键字" size="small" prefix-icon="el-icon-search" clearable />
        <el-button type="primary" size="small" @click="addDialogVisiable = true">上传视频</el-button>
      </div>
      <div class="order-rule">
        <p>
          <span class="publicStatus active" @click="isPublic(0)">已发布</span>
          <span class="publicStatus" @click="isPublic(1)">待审核</span>
          <span class="publicStatus" @click="isPublic(2)">未通过</span>
        </p>
        <div v-show="publicStatus == 0">
          <span class="orderway active" @click="order(0)">综合排序</span>
          <span class="orderway" @click="order(1)">最多点赞</span>
          <span class="orderway" @click="order(2)">最多播放</span>
          <span class="orderway" @click="order(3)">最新发布</span>
        </div>
      </div>
      <div  v-if="tableData.length == 0">
        暂无数据
      </div>
      <div v-else class="card-container" @click="gotoPlayVideo($event)">
        <el-card class="video-card play" :videoid="item.id" v-for="item of data" :key="item.id" shadow="hover" :body-style="{ padding: '0px'}">
          <div class="card-hover">
            <el-button type="primary" size="small" @click.stop="handleEdit(item)">编辑</el-button>
            <el-button type="danger" size="small" @click.stop="handleDelete(item.id)">删除</el-button>
          </div>
          <img class="img-pic" id="a" :videoName="item.videoName" :url="item.url" :src="getUrl(item.pic)">
          <div class="content-wrapper">
            <span class="card-title" :videoName="item.videoName" :url="item.url">{{item.videoName}}</span>
            <i class="iconfont icon-avatar1"> {{item.authorName}}</i>
            <i class="iconfont icon-play1"> {{changeNumber(item.playNumber)||0}}</i>
            <i class="iconfont icon-clock1"> {{item.createTime?attachDate(item.createTime):"未发布"}}</i>
            <i class="iconfont icon-good"> {{changeNumber(item.praise)||0}}</i>
          </div>
        </el-card>
      </div>
      <!-- 添加视频框 -->
    <el-dialog title="添加新视频" :visible.sync="addDialogVisiable" center width="400px">
      <el-form :model="registerForm" id="add-form" ref="registerForm" :rules="rules" label-width="80px" :inline="false" size="small" enctype="multipart/form-data">
        <el-form-item prop="videoName" label="视频名字" size="mini">
          <el-input v-model="registerForm.videoName" maxlength="30" name="videoName" placeholder="视频名字"></el-input>
        </el-form-item>
        <el-form-item prop="style" label="视频风格" size="mini">
          <el-select v-model="registerForm.style" name="style" placeholder="请选择">
            <el-option
              v-for="item in videoStyles"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="introduction" label="视频简介" size="mini">
          <el-input v-model="registerForm.introduction" maxlength="10000" name="introduction" type="textarea" placeholder="视频简介"></el-input>
        </el-form-item>
        <el-form-item prop="url" accept="video/*" label="视频内容" size="mini">
          <input type="file" @change="previewVideo()" name="file" id="new_video_url" >
        </el-form-item>
        <el-form-item prop="pic" accept="image/*" label="视频封面" size="mini">
          <input type="file" name="file" id="video_pic">
        </el-form-item>
      </el-form>
      <div class="video-wrap">
        <video :src="video0Url" style="height:200px" id="video0"></video>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="addVideo">确定</el-button>
        <el-button @click="addDialogVisiable = false">取消</el-button>
      </span>
    </el-dialog>

      <!-- 翻页 -->
      <div class="pagination">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="15"
          layout="total, prev, pager, next, jumper"
          :total="tableData.length"
          background>
        </el-pagination>
      </div>
      <!-- 修改视频框 -->
    <el-dialog title="修改视频" :visible.sync="editVisiable" center width="400px">
      <el-form :model="form" id="edit-form" ref="form" :rules="rules" label-width="80px" :inline="false" size="small">
        <el-form-item prop="authorId" label="作者ID" size="mini">
          <el-input v-model="form.authorId" name="authorId" placeholder="作者ID"></el-input>
        </el-form-item>
        <el-form-item prop="videoName" label="视频名字" size="mini">
          <el-input v-model="form.videoName" maxlength="30" name="videoName" placeholder="视频名字"></el-input>
        </el-form-item>
        <el-form-item prop="style" label="视频风格" size="mini">
          <el-select v-model="form.style" name="style" placeholder="请选择">
            <el-option
              v-for="item in videoStyles"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="introduction" label="视频简介" size="mini">
          <el-input v-model="form.introduction" maxlength="10000" name="introduction" type="textarea" placeholder="视频简介"></el-input>
        </el-form-item>
        <el-form-item v-if="publicStatus==2" prop="cause" label="退回原因" size="mini">
          <el-input v-model="form.cause" maxlength="10000" name="cause" type="textarea" placeholder="无" disabled></el-input>
        </el-form-item>
        <el-form-item prop="url" accept="video/*" label="视频内容" size="mini">
          <input type="file" @change="previewVideo2()" name="file" id="edit_video_url" >
        </el-form-item>
        <el-form-item prop="pic" accept="image/*" label="视频封面" size="mini">
          <input type="file" name="file" id="video_pic">
        </el-form-item>
      </el-form>
      <video :src="video1Url" style="height:200px" id="video1"></video>
      <span slot="footer">
        <el-button type="primary" @click="editVideo">确定</el-button>
        <el-button @click="editVisiable = false">取消</el-button>
      </span>
    </el-dialog>

    <!-- 删除框 -->
    <el-dialog title="删除视频" :visible.sync="delVisible" center width="300px">
      <div align="center">删除不可恢复，是否确定删除？</div>
      <span slot="footer">
        <el-button type="primary" @click="deleteRow">确定</el-button>
        <el-button @click="delVisible = false">取消</el-button>
      </span>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {getByAuthorId,updateVideo,delVideo,delUnCheckVideo,getUnCheckByAuthorId,setUnCheckVideo,updateUnCheckVideo} from '../api/index'
import {videoStyles} from '../assets/data/videoStyles'
import {mixin} from '../mixins/index'
export default {
  name:'contribute',
  mixins:[mixin],
  data(){
    return {
      publicStatus:0,     //是否已发布 0已发布 1未审核 2未通过
      search_text:'',  //筛选的关键字
      sortord:0,       //排序方式
      tableData:[],    //显示的视频信息
      addDialogVisiable:false,  //添加视频框
      editVisiable:false,
      delVisible:false,
      video0Url:'',
      video1Url:'',
      videoDuration:'',  //视频长度
      videoStyles:[],    //视频风格
      currentPage:1,  //当前页
      pageSize:18,    //每一页个数
      registerForm:{  //添加新视频表
        videoName:'',
        style:'',
        introduction:'',
        cause:'',
      },
      form:{  //修改视频表
        id:-1,
        authorId:'',
        videoName:'',
        style:'',
        introduction:'',
      },
      rules:{         //添加视频规则
        videoName:[
          {required:true,message:'请输入视频名字',trigger:'blur'}
        ],
        style:[
          {required:true,message:'请选择视频风格',trigger:'blur'},
        ],
        introduction:[
          {required:false,message:'请输入视频简介',trigger:'blur'},
        ],
      }
    }
  },
  watch:{
    search_text:function(){
      if(this.search_text == ''){
        this.tableData = this.tempData
      }else{
        this.tableData = []
        for(let item of this.tempData){
          if(item.videoName.includes(this.search_text)){
            this.tableData.push(item)
          }
        }
      }
    },
    sortord(v){
      document.getElementsByClassName('orderway')[0].classList.remove('active')
      document.getElementsByClassName('orderway')[1].classList.remove('active')
      document.getElementsByClassName('orderway')[2].classList.remove('active')
      document.getElementsByClassName('orderway')[3].classList.remove('active')
      document.getElementsByClassName('orderway')[v].classList.add('active')
      switch (v) {
        case 0:
          this.tableData.sort(function (a, b) {
            if (a.praise != 0 ||b.praise != 0) {
              let a1 = (a.praise/a.playNumber) ? (a.praise/a.playNumber) : 0
              let b1 = (b.praise/b.playNumber) ? (b.praise/b.playNumber) : 0
              return b1 - a1;
            }
            return b.playNumber - a.playNumber;
          });
          break;
        case 1:  //根据点赞数排序
          this.tableData.sort(function (a, b) {
            if (a.praise != b.praise) {
              return b.praise - a.praise;
            }
            return b.playNumber - a.playNumber;
          });
          break;
        case 2:  //根据播放量排序
          this.tableData.sort(function (a, b) {
            return b.playNumber - a.playNumber;
          });
          break;
        case 3: //根据创建时间排序
          this.tableData.sort(function (a, b) {
            let x = a.createTime
            let y = b.createTime
            let a1 = x.slice(0,4)+x.slice(5,7)+x.slice(8,10)+x.slice(11,13)+x.slice(14,16)+x.slice(17,19)
            let b1 = y.slice(0,4)+y.slice(5,7)+y.slice(8,10)+y.slice(11,13)+y.slice(14,16)+y.slice(17,19)
            return a1 - b1;
          });
          break;
      }
    },
    publicStatus(v){
      document.getElementsByClassName('publicStatus')[0].classList.remove('active')
      document.getElementsByClassName('publicStatus')[1].classList.remove('active')
      document.getElementsByClassName('publicStatus')[2].classList.remove('active')
      document.getElementsByClassName('publicStatus')[v].classList.add('active')
      if(v == 0){
        this.getData1()
      }else{
        this.getData2()
      }
    }
  },
  computed:{
    data(){
      return this.tableData.slice((this.currentPage-1)*this.pageSize, this.currentPage*this.pageSize)
    },
    ...mapGetters(['userId'])
  },
  created(){
    this.getData1()
  },
  mounted(){
    this.videoStyles = videoStyles
  },
  methods:{
    //获取已发布视频
    getData1(){
      this.tempData=[]
      this.tableData=[]
        getByAuthorId(this.userId)
          .then(res =>{
            this.tempData = res
            this.currentPage = 1
            this.tempData.sort(function (a, b) {
              return b.praise/b.playNumber - a.praise/a.playNumber;
            });
            this.tableData = this.tempData
          }).catch(err =>{
            console.log(err);
          })
    },
    //未审核视频
    getData2(){
      this.tempData=[]
      this.tableData=[]
        getUnCheckByAuthorId(this.userId)
          .then(res =>{
            if (this.publicStatus == 1) {
              for(let item in res){
                if (res[item].checked == 0) {
                  this.tempData.push(res[item])
                }
              }
            }
            if (this.publicStatus == 2) {
              for(let item in res){
                if (res[item].checked == 1) {
                  this.tempData.push(res[item])
                }
              }
            }
            this.tableData = this.tempData
            this.currentPage = 1
          }).catch(err =>{
            console.log(err);
          })
    },
    addVideo(){
      this.$refs['registerForm'].validate(valid =>{
        if(valid){
          var formData = new FormData(document.getElementById("add-form"));
          formData.append('duration',parseInt(this.videoDuration))
          formData.append('authorId',this.userId)
          setUnCheckVideo(formData)
          .then(res =>{
            if(res.code == 1){
              this.notify("添加成功","success")
            }else{
              this.notify(res.msg,"error")
            }
          }).catch(err => {
            console.log(err)
          })
          this.addDialogVisible = false;
        }
      })
    },
    previewVideo(){
      var video = document.getElementById("new_video_url");
      try {
        var objURL = this.getObjectURL(video.files[0]);
      } catch (err) {
        this.video0Url = ''
        this.videoDuration = ''
        return 
      }
      const isVideo = (video.files[0].type === 'video/mp4')
      if(isVideo){
        this.video0Url = objURL
      }else{
        this.video0Url = ''
      }
      var video0 = document.getElementById("video0");
      setTimeout(() => {
        this.videoDuration = video0.duration
      }, 100);
    },
    previewVideo2(){
      var video = document.getElementById("edit_video_url");
      try {
        var objURL = this.getObjectURL(video.files[0]);
      } catch (err) {
        this.video0Url = ''
        this.videoDuration = ''
        return 
      }
      const isVideo = (video.files[0].type === 'video/mp4')
      if(isVideo){
        this.video1Url = objURL
      }else{
        this.video1Url = ''
      }
      var video1 = document.getElementById("video1");
      setTimeout(() => {
        this.videoDuration = video1.duration
      }, 100);
    },
    //获取地址
    getObjectURL(file) {
        var url = null;
        if (window.createObjectURL) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    },
    isPublic(v){
      this.publicStatus = v
    },
    //排序方式
    order(way){
      this.sortord = way
    },
    //获取当前页
    handleCurrentChange(val){
      this.currentPage = val;
    },
    //编辑视频信息
    handleEdit(row){
      if(this.publicStatus == 0){
        this.notify('已发布视频无法修改','warning')
      }else{
        this.form = []
        this.form = {
          id:row.id,
          authorId:row.authorId,
          videoName:row.videoName,
          style:row.style,
          introduction:row.introduction,
          cause:row.cause
        }
        this.editVisiable = true;
      }
    },
    editVideo(){
      this.$refs['form'].validate(valid =>{
        if(valid){
          var formData = new FormData(document.getElementById("edit-form"));
          formData.append('id',this.form.id)
          formData.append('duration',parseInt(this.videoDuration))
          if (this.publicStatus == 0) {
            updateVideo(formData)
              .then(res =>{
                if(res.code==1){
                  this.getData1()
                  this.notify('修改成功','success')
                }else{
                  this.notify('修改失败','error')
                }
              }).catch(err => {
                console.log(err)
            })
          }else{
            formData.append('checked',0)
            updateUnCheckVideo(formData)
              .then(res =>{
                if(res.code==1){
                  this.getData2()
                  this.notify('修改成功','success')
                }else{
                  this.notify('修改失败','error')
                }
              }).catch(err => {
              console.log(err)
            })
          }
          
          this.editVisible = false;
        }
      })
    },
    //弹出是否删除窗口
    handleDelete(id){
      this.idx = id
      this.delVisible = true
    },
    //删除视频
    deleteRow(){
      if (this.publicStatus == 0) {
        delVideo(this.idx)
        .then(res =>{
            if (res) {
              this.getData1();
              this.notify('删除成功','success')
            }else{
              this.notify('删除失败','error')
            }
          })
      }else{
        delUnCheckVideo(this.idx)
          .then(res =>{
            if (res) {
              this.getData2();
              this.notify('删除成功','success')
            }else{
              this.notify('删除失败','error')
            }
          })
      }
      
      this.delVisible = false
    },
  }
}
</script>

<style scoped>
@import '../assets/css/contribute.css';
</style>